﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5_NovaAdmin.Infrastructure.Extensions
{
    public static class SqlSugarExtensions
    {
        /// <summary>
        /// 自动填充关联数据
        /// </summary>
        /// <param name="mainDb"></param>
        /// <param name="entity"></param>
        public static void FillForeignData(this SqlSugarScope mainDb, object entity)
        {
            var entityType = entity.GetType();
            var foreignProps = entityType.GetProperties()
                .Where(p => p.IsDefined(typeof(ForeignDataAttribute), inherit: false));

            foreach (var prop in foreignProps)
            {
                var attr = prop.GetCustomAttribute<ForeignDataAttribute>();
                // 获取外键值（如 DeptId）
                var foreignKeyProp = entityType.GetProperty(attr.ForeignKey);
                if (foreignKeyProp == null) continue;

                var foreignKeyValue = foreignKeyProp.GetValue(entity);
                if (foreignKeyValue == null) continue;

                // 动态查询关联表
                var sourceEntity = attr.SourceEntity.Name.ToString();
                var sourceField = attr.SourceField;
                var queryField = attr.QueryField;

                // 当前连接未释放，不能共用，所以要创建新的 SqlSugar 实例（独立连接）
                using (var subDb = new SqlSugarScope(mainDb.CurrentConnectionConfig))
                {
                    // 构建查询
                    var foreignValue = subDb.Queryable<object>().AS(sourceEntity, "o")
                    .Where($"{queryField} = @value", new { value = foreignKeyValue })
                          .Select(sourceField)
                          .First();
                    var expando = foreignValue as ExpandoObject;
                    if (expando != null)
                    {
                        var dictionary = (IDictionary<string, object>)expando;
                        // 通过字典获取你需要的属性  
                        if (dictionary.TryGetValue(sourceField, out var yourValue))
                        {
                            prop.SetValue(entity, yourValue is DBNull ? null : yourValue.ToString());
                        }
                    }
                }
            }
        }
    }
}
